package com.elite.controller;

import com.alibaba.fastjson.JSON;
import com.elite.entity.*;
import com.elite.service.FileService;
import com.elite.service.GoodsService;
import com.elite.service.ShoppingCartService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.logging.Logger;

/**
 * Created by Administrator on 2017/2/12.
 */
@RestController
@RequestMapping("/details")
public class DetailsController {

    @Autowired
    private GoodsService goodsService;
    @Autowired
    private HttpSession session;
    @Autowired
    private HttpServletRequest request;
    @Autowired
    private HttpServletResponse response;
    @Autowired
    private FileService fileService;
    @Autowired
    private ShoppingCartService shoppingCartService;


    private static final Logger LOGGER = Logger.getLogger(String.valueOf(DetailsController.class));

    /**
     * 把数据传向details页面
     * @param goodsId
     * @return
     */
    @RequestMapping(value = "/selectGoods",produces = "text/html;charset=UTF-8")
    @ResponseBody
    public String details(Integer goodsId){

        Map<String,Object> map = new HashMap<String, Object>();
        Goods goods = null;
        try {
            goods = goodsService.selectByPrimaryKey(goodsId);
        }catch (NullPointerException e){
            e.printStackTrace();
        }

        if (goods != null){

            map.put("goodsName",goods.getGoodsName());
            map.put("goodsPrice",goods.getGoodsPrice());
            map.put("goodsUnit", goods.getGoodsUnit());
            map.put("goodsIntroducts", goods.getGoodsIntroducts());
            map.put("goodsSize",goods.getGoodsSize());

        }


        return JSON.toJSON(map).toString();
    }

    /**
     * 把相关商品的图片传给details页面
     * @param goodsId
     * @return
     */
    @RequestMapping(value = "/selectGoodsPic",produces = "text/html;charset=UTF-8")
    @ResponseBody
    public String detailsPic(Integer goodsId){


        List<File> fileList = new ArrayList<File>();
        List<FileGoods> fileGoodses = null;

        try{
            fileGoodses = goodsService.selectByGoodsId(goodsId);
        } catch (NullPointerException e){
            e.printStackTrace();
        }

        FileGoods fileGoods = null;
        if (fileGoodses != null && fileGoodses.size() != 0) {
            fileGoods = fileGoodses.get(0);
        }

        if (fileGoods != null ){
                File file = fileService.selectByPrimaryKey(fileGoods.getFileId());
                if (file != null){
                    fileList.add(file);
                }
        }

        return JSON.toJSON(fileList).toString();
    }


    /**
     * details页面把商品加入购物车
     * @param goodsId
     * @param goodsSize
     */
    @RequestMapping(value = "/addShopCart",method = RequestMethod.POST)
    @ResponseBody
    public void addShopCart(Integer goodsId,Integer goodsSize){
  LOGGER.info("------------------>>>>>>>>>>>>>>,ID,Size" + goodsId + goodsSize);

        Goods goods = null;
        try {
            goods = goodsService.selectByPrimaryKey(goodsId);
        }catch (NullPointerException e){
            e.printStackTrace();
        }
        User user = null;
        try {
            user = (User) session.getAttribute("loginUser");
        } catch (NullPointerException e){
            e.printStackTrace();
        }



        if (user != null){

            if (goods != null) {
                if (goods.getGoodsSize() > 0){

                    Integer userId = user.getUserId();

                    ShoppingCart shoppingCart1 = null;
                    try {
                        shoppingCart1 = shoppingCartService.selectByByUserIdAndGoodsId(userId,goodsId);
                    } catch (NullPointerException e){
                        e.printStackTrace();
                    }

                    if (shoppingCart1 != null){
                        if (goodsSize != null && shoppingCart1.getGoodsSize()+goodsSize <= goods.getGoodsSize()){
                            shoppingCart1.setGoodsSize(shoppingCart1.getGoodsSize()+goodsSize);
                            shoppingCart1.setTotalprice(shoppingCart1.getTotalprice()+goodsSize*goods.getGoodsPrice());
                            shoppingCartService.updateByPrimaryKey(shoppingCart1);
                        }

                    }else {

                        List<FileGoods> fileGoodses = null;

                        try{
                            fileGoodses = fileService.selectByGoodsId(goodsId);
                        } catch (NullPointerException e){
                            e.printStackTrace();
                        }

                        int index = 0;
                        if (fileGoodses != null && fileGoodses.size() != 0) {
                            index = (int) (Math.random()*fileGoodses.size());
                        }
                        FileGoods fileGoods = null;
                        if (fileGoodses != null && fileGoodses.size() != 0) {
                            fileGoods = fileGoodses.get(index);
                        }

                        File file = null;
                        if (fileGoods != null) {
                            file = fileService.selectByPrimaryKey(fileGoods.getFileId());
                        }
                        if (goodsSize != null && goodsSize <= goods.getGoodsSize()){

                            if (file != null){

                                ShoppingCart shoppingCart = new ShoppingCart();
                                shoppingCart.setGoodsId(goodsId);
                                shoppingCart.setUserId(userId);
                                shoppingCart.setFileUrl(file.getFileUrl());
                                shoppingCart.setGoodsName(goods.getGoodsName());
                                shoppingCart.setGoodsIntroducts(goods.getGoodsIntroducts());
                                shoppingCart.setGoodsCity(goods.getGoodsCity());
                                shoppingCart.setGoodsSize(goodsSize);
                                shoppingCart.setTotalprice(goodsSize * goods.getGoodsPrice());
                                shoppingCartService.addShoppingCart(shoppingCart);

                            }
                        }

                    }

                }
            }
        }else {
            try {
                response.sendRedirect(request.getContextPath() + "/resources/seller_login.html");
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

}
